<script setup lang="ts">
import { reactive, ref } from "vue";
import { onUnload } from "@dcloudio/uni-app";
import { useEventChannel } from "@/hooks/page";
import { user_edit_intro_api } from "@/package/my/api/guider_didi";
import { Toast } from "@/utils/toast";

import FormButton from "@/components/form/button.vue";

onUnload(() => eventChannel?.emit("ev-info-data", ""));

const inputValue = ref("");
const configData = reactive({
  placeholder: "写点什么吧~",
  maxLength: 50,
});

const saveClick = () => {
  const _inputValue = inputValue.value;
  if (_inputValue.length === 0) return;
  Toast.showLoading();
  user_edit_intro_api({ edit_intro: _inputValue })
    .then(() => {
      Toast.hideLoading();
      eventChannel?.emit("ev-info-data", _inputValue);
    })
    .catch(() => Toast.hideLoading());
};

const keyData = {
  autograph: {
    title: "编辑简介",
  },
};

const eventChannel = useEventChannel(() => {
  eventChannel?.once("ev-info-data", (resp) => {
    console.log("ev-info-data", resp);

    const key = resp.key;
    const data = (keyData as any)[key];
    uni.setNavigationBarTitle({ title: data.title });
    inputValue.value = resp.value;

    tempData.key = key;
  });
});

const tempData = { key: "" };
</script>

<template>
  <view class="edit-form">
    <textarea
      class="edit-form-textarea"
      v-model="inputValue"
      auto-height
      :placeholder="configData.placeholder"
      :maxlength="configData.maxLength"
    />

    <view class="edit-form-limit">
      （{{ inputValue.length }}/{{ configData.maxLength }}）
    </view>
  </view>

  <view class="edit-btn">
    <view @click="saveClick">
      <FormButton :disabled="inputValue.length === 0">保存</FormButton>
    </view>
  </view>
</template>

<style lang="scss">
page {
  padding-top: 20rpx;
  background-color: #ffffff;
}

.edit-form {
  padding-bottom: 30rpx;
  margin: 0 30rpx;
  border-radius: 20rpx;
  background-color: #f8f8f8;

  .edit-form-textarea {
    display: block;
    width: 100%;
    min-height: 240rpx;
    padding: 30rpx;
    font-size: 28rpx;
    color: #333333;
    line-height: 40rpx;
    box-sizing: border-box;
  }

  .edit-form-limit {
    padding-right: 30rpx;
    font-size: 28rpx;
    color: #999999;
    line-height: 40rpx;
    text-align: right;
  }
}

.edit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}
</style>